package com.borqsprocessmanager.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.borqsprocessmanager.ProcessSettingManager;

public class CPUFreqSetting {
    private final String TAG = "CPUFreqSetting";
    /**
     * cpu cat命令大全 cat [%cpuFreqPath%]/cpuinfo_cur_freq (当前cpu频率) cat
     * [%cpuFreqPath%]/cpuinfo_max_freq (最大cpu频率) cat
     * [%cpuFreqPath%]/cpuinfo_min_freq (最小cpu频率) cat
     * [%cpuFreqPath%]/related_cpus (cpu数量标号,从0开始,如果是双核,结果为0,1) cat
     * [%cpuFreqPath%]/scaling_available_frequencies (cpu所有可用频率) cat
     * [%cpuFreqPath%]/scaling_available_governors (cpu所有可用调控模式) cat
     * [%cpuFreqPath%]/scaling_available_governors (cpu所有可用调控模式) cat
     * [%cpuFreqPath%]/scaling_cur_freq (?????) cat
     * [%cpuFreqPath%]/scaling_driver (?????) cat
     * [%cpuFreqPath%]/scaling_governor (?????) cat
     * [%cpuFreqPath%]/scaling_max_freq (?????) cat
     * [%cpuFreqPath%]/scaling_min_freq (?????) cat
     * [%cpuFreqPath%]/scaling_setspeed (?????) cat
     * [%cpuFreqPath%]/cpuinfo_transition_latency (?????)
     */

    public static final int TAG_ONDEMAND = 0;
    public static final int TAG_USERSPACE = 1;
    public static final int TAG_POWERSAVE = 2;

    private final String CPU_FREQ_PATH = "/sys/devices/system/cpu/cpu0/cpufreq";

    private final String MIN_CPUFREQ = "cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq";
    private final String USER_CPUFREQ_ECHO = "echo ";
    private final String USER_CPUFREQ = " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed";

    public static final String PERFORMANCE_GOVERNOR = "performance";
    public static final String POWER_SAVE_GOVERNOR = "powersave";
    public static final String ONDEMAND_GOVERNOR = "ondemand";
    public static final String CONSERVATIVE_GOVERNOR = "performance";
    public static final String USERSAPCE_GOVERNOR = "userspace";

    // public void powerSaveGovernor() {
    // List<String> governors = readCpuGovernors();
    // if (governors.contains(object)) {
    //
    // }
    // }

    /**
     * 获得当前CPU调控模式
     */
    public void getCpuCurGovernor() {
        try {
            DataInputStream is = null;
            Process process = Runtime.getRuntime().exec(
                    "cat " + CPU_FREQ_PATH + "/scaling_governor");
            is = new DataInputStream(process.getInputStream());
            String line = is.readLine();
            Log.v(TAG, "line===" + line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重写CPU调控模式
     * 
     * @param governor
     * @return
     */
    private boolean writeCpuGovernor(String governor) {
        DataOutputStream os = null;
        byte[] buffer = new byte[256];
        String command = "echo " + governor + " > " + CPU_FREQ_PATH
                + "/scaling_governor";
        Log.v(TAG, "command: " + command);
        try {
            Process process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
            Log.v(TAG, "exit value = " + process.exitValue());
        } catch (IOException e) {
            Log.v(TAG, "writeCpuGovernor: write CPU Governor(" + governor
                    + ") failed!");
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 获得CPU所有调控模式
     * 
     * @return
     */
    public List<String> readCpuGovernors() {
        List<String> governors = new ArrayList<String>();
        DataInputStream is = null;
        try {
            Process process = Runtime.getRuntime().exec(
                    "cat " + CPU_FREQ_PATH + "/scaling_available_governors");
            is = new DataInputStream(process.getInputStream());
            String line = is.readLine();

            String[] strs = line.split(" ");
            for (int i = 0; i < strs.length; i++)
                governors.add(strs[i]);
        } catch (IOException e) {
            Log.v(TAG, "readCpuGovernors: read CPU Governors failed!");
        }
        return governors;
    }

    public void setUserSpaceMod(int cpuMode) {
        switch (cpuMode) {
        case TAG_ONDEMAND:
            writeCpuGovernor(ONDEMAND_GOVERNOR);

            break;

        case TAG_POWERSAVE:
            writeCpuGovernor(POWER_SAVE_GOVERNOR);

            break;

        case TAG_USERSPACE:
            writeCpuGovernor(USERSAPCE_GOVERNOR);
            String minCpufreq = getMinCpufreq();
            Log.v(TAG, "minCpufreq===" + minCpufreq);
            setUserSpaceCpuFreq(minCpufreq);
            break;

        default:
            break;
        }
    }

    public String getMinCpufreq() {
        String minCpuFreq = ProcessSettingManager.runRootCommand(MIN_CPUFREQ);
        Log.v(TAG, "min_Cpu_Freq===" + minCpuFreq);
        return minCpuFreq;

    }

    public void setUserSpaceCpuFreq(String minCpuFreq) {
        ProcessSettingManager.runRootCommand(USER_CPUFREQ_ECHO + " "
                + minCpuFreq + " " + USER_CPUFREQ);
        // ProcessSettingManager
        // .runRootCommand(" echo 1512000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");

    }
}
